using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Configuration;

namespace FileHound {
	public class Watcher : System.Windows.Forms.Form {
		#region ======================= Properties & Controls ======================
		Hound.Properties.Settings Settings;
		private System.Windows.Forms.Label lblInfo;
		private System.ComponentModel.IContainer components;
	
		private string Info{set{lblInfo.Text += value+Environment.NewLine;Application.DoEvents();}}
		public PDFHound pdfHound = null;
		public TiffHound tiffHound = null;
		private System.Windows.Forms.Timer timer1;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label lblPDFServer;
		private System.Windows.Forms.Label lblOCRServer;
		private System.Windows.Forms.Label label4;
		private Button btnBrows;
		private FolderBrowserDialog watchFolderDlg;
		public CheckBox chkNoXML;
		private FileSystemWatcher fsw;
		#endregion =================================================================

		#region ======================= Form =======================================
		public Watcher() {
			InitializeComponent();
		}
		[STAThread]
		static void Main() {
			Application.Run(new Watcher());
		}
		private void Watcher_Load(object sender, System.EventArgs e) {
			if( Common.DebugMode && MessageBox.Show("Continue in DEBUG MODE?","Debug Mode",MessageBoxButtons.YesNo) == DialogResult.No ) {
				Close();
				return;
			}
			Settings = new Hound.Properties.Settings();
			if (Settings.NoXml && MessageBox.Show("NoXml is true! Continue?", "Danger!", MessageBoxButtons.YesNo) == DialogResult.No) {
				Close();
				return;
			}

			if (!Settings.SendImages && !Settings.ExtraBCR) {
				MessageBox.Show(this, "Must select Images or BarCodes", "Hound");
				return;
			}

			if (Settings.SendImages) pdfHound = new PDFHound(this);
			if(Settings.ExtraBCR) tiffHound = new TiffHound(this);
			if(Settings.Watch_Folder == "") btnBrows_Click(null,null);
			if(Settings.Watch_Folder == "") {
				this.Close();
				return;
			}
			StartFileWatcher(Settings.Watch_Folder);
			Info = "Current directory:"+Directory.GetCurrentDirectory();
			Info = "ThreadsCountMax:" +  (pdfHound!=null ? pdfHound.ThreadsCountMax: tiffHound.ThreadsCountMax);
			Info = "WebService:" + Settings.Hound_com_onrefund_Imaging;
			if( pdfHound != null) pdfHound.Show();
			if( tiffHound != null ) tiffHound.Show();
			FireOnCreated(Settings.Watch_Folder);
			Text += "(" + Application.ProductVersion + ")";
		}
		private void Watcher_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
			if (pdfHound != null) pdfHound.Close();
			if (tiffHound != null) tiffHound.Close();
		}
		#endregion =================================================================

		#region ======================= Windows Form Designer ======================
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Watcher));
			this.lblInfo = new System.Windows.Forms.Label();
			this.timer1 = new System.Windows.Forms.Timer(this.components);
			this.label1 = new System.Windows.Forms.Label();
			this.lblPDFServer = new System.Windows.Forms.Label();
			this.lblOCRServer = new System.Windows.Forms.Label();
			this.label4 = new System.Windows.Forms.Label();
			this.btnBrows = new System.Windows.Forms.Button();
			this.watchFolderDlg = new System.Windows.Forms.FolderBrowserDialog();
			this.chkNoXML = new System.Windows.Forms.CheckBox();
			this.SuspendLayout();
			// 
			// lblInfo
			// 
			this.lblInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
									| System.Windows.Forms.AnchorStyles.Right)));
			this.lblInfo.AutoSize = true;
			this.lblInfo.Location = new System.Drawing.Point(8, 8);
			this.lblInfo.Name = "lblInfo";
			this.lblInfo.Size = new System.Drawing.Size(0, 13);
			this.lblInfo.TabIndex = 0;
			// 
			// timer1
			// 
			this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
			// 
			// label1
			// 
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(2, 70);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(68, 13);
			this.label1.TabIndex = 1;
			this.label1.Text = "PDF Server: ";
			// 
			// lblPDFServer
			// 
			this.lblPDFServer.AutoSize = true;
			this.lblPDFServer.Location = new System.Drawing.Point(72, 48);
			this.lblPDFServer.Name = "lblPDFServer";
			this.lblPDFServer.Size = new System.Drawing.Size(0, 13);
			this.lblPDFServer.TabIndex = 2;
			// 
			// lblOCRServer
			// 
			this.lblOCRServer.AutoSize = true;
			this.lblOCRServer.Location = new System.Drawing.Point(72, 64);
			this.lblOCRServer.Name = "lblOCRServer";
			this.lblOCRServer.Size = new System.Drawing.Size(0, 13);
			this.lblOCRServer.TabIndex = 4;
			// 
			// label4
			// 
			this.label4.AutoSize = true;
			this.label4.Location = new System.Drawing.Point(2, 86);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(70, 13);
			this.label4.TabIndex = 3;
			this.label4.Text = "OCR Server: ";
			// 
			// btnBrows
			// 
			this.btnBrows.Location = new System.Drawing.Point(385, 8);
			this.btnBrows.Name = "btnBrows";
			this.btnBrows.Size = new System.Drawing.Size(75, 23);
			this.btnBrows.TabIndex = 5;
			this.btnBrows.Text = "Brows";
			this.btnBrows.UseVisualStyleBackColor = true;
			this.btnBrows.Click += new System.EventHandler(this.btnBrows_Click);
			// 
			// chkNoXML
			// 
			this.chkNoXML.AutoSize = true;
			this.chkNoXML.Location = new System.Drawing.Point(385, 38);
			this.chkNoXML.Name = "chkNoXML";
			this.chkNoXML.Size = new System.Drawing.Size(65, 17);
			this.chkNoXML.TabIndex = 6;
			this.chkNoXML.Text = "No XML";
			this.chkNoXML.UseVisualStyleBackColor = true;
			this.chkNoXML.CheckedChanged += new System.EventHandler(this.chkNoXML_CheckedChanged);
			// 
			// Watcher
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(472, 99);
			this.Controls.Add(this.chkNoXML);
			this.Controls.Add(this.btnBrows);
			this.Controls.Add(this.lblOCRServer);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.lblPDFServer);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.lblInfo);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "Watcher";
			this.Text = "File Watcher";
			this.Activated += new System.EventHandler(this.Watcher_Activated);
			this.Closing += new System.ComponentModel.CancelEventHandler(this.Watcher_Closing);
			this.Load += new System.EventHandler(this.Watcher_Load);
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		protected override void Dispose( bool disposing ) {
			if( disposing ) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		#endregion =================================================================

		#region ======================= File Watcher ===============================
		public event FileCreatedDelegate FileCreated;
		protected void OnFileCreated(FileCreatedEventArgs e) {
			try {
				FileCreated(this,e);
			} catch(Exception exc) {
				MessageBox.Show(this,exc.ToString());
			}
		}
		protected void StartFileWatcher(string directory) {
			if( !CheckPath(directory) )return;
			fsw = new FileSystemWatcher(directory);
			fsw.IncludeSubdirectories = true;
			fsw.EnableRaisingEvents = true;
			fsw.Created += new FileSystemEventHandler(OnCreated);
			SetDefaultInfo();
		}
		protected void OnCreated(object sender, FileSystemEventArgs e) {
			FileCreatedEventArgs OnFileCreatedEventArgs = new FileCreatedEventArgs(e.FullPath);
			OnFileCreated(OnFileCreatedEventArgs);
		}
		#endregion =================================================================

		#region ======================= Helpers ====================================
		protected bool CheckPath(string path) {
			if( Directory.Exists(path) )return true;
			if( MessageBox.Show("Path "+path+" does not exists. Create?","Watched Path",MessageBoxButtons.YesNo) == DialogResult.No )return false;
			Directory.CreateDirectory(path);
			return true;
		}
		private void FireOnCreated(string folder){
			foreach(string file in Directory.GetFiles(folder))
				OnCreated(null,new FileSystemEventArgs(WatcherChangeTypes.All,folder,Path.GetFileName(file)));
			foreach (string subFolder in Directory.GetDirectories(folder))
				FireOnCreated(subFolder);
		}
		protected void SetDefaultInfo(){ Info = "Watching "+Settings.Watch_Folder; }
		#endregion =================================================================

		private void Watcher_Activated(object sender, System.EventArgs e) {
			timer1.Interval = 1000;
			timer1.Enabled = true;
			timer1.Start();
		}

		private void timer1_Tick(object sender, System.EventArgs e) {
			timer1.Enabled = false;
			if (pdfHound != null) {
				pdfHound.WindowState = WindowState;
				pdfHound.BringToFront();
			}
			if (tiffHound != null) {
				tiffHound.WindowState = WindowState;
				tiffHound.BringToFront();
			}
		}

		private void btnBrows_Click(object sender,EventArgs e) {
			watchFolderDlg.SelectedPath = Settings.Watch_Folder;
			if(watchFolderDlg.ShowDialog(this) != DialogResult.OK) return;
			Settings.Watch_Folder = watchFolderDlg.SelectedPath;
			Settings.Save();
			MessageBox.Show(this,"Must restart hound to take affect.");
		}

		private void chkNoXML_CheckedChanged(object sender, EventArgs e) {

		}
	}
	public delegate void FileCreatedDelegate(object sender, FileCreatedEventArgs e);

	public class FileCreatedEventArgs: EventArgs {
		public string FullName;
		public string Name;
		public string Extention;
		public string Directory;

		public FileCreatedEventArgs(string file) {
			this.FullName = file;
			this.Name = Path.GetFileName(file);
			this.Directory = Path.GetDirectoryName(file);
			this.Extention = Path.GetExtension(file);
		}
	}
}